// Copyright (c) 2000 Just Objects B.V. <just@justobjects.nl>
// Distributable under LGPL license. See terms of license at gnu.org.

package nl.justobjects.pushlet.core;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

/**
 * ClientAdapter that sends Events as XML.
 *
 * @version $Id: XMLPushletAdapter.java,v 1.5 2003/08/15 08:37:40 justb Exp $
 * @author Just van den Broecke - Just Objects &copy;
 */
class XMLPushletAdapter implements ClientAdapter {
	ServletOutputStream out = null;

	public void start() throws IOException {
	}

	public void init(HttpServletRequest req,
					 HttpServletResponse rsp) throws IOException {

		debug("PROTOCOL=" + req.getProtocol());
        Enumeration e =req.getHeaderNames();
		while (e.hasMoreElements()) {
			String nextName = (String) e.nextElement();
			debug("name=" + nextName + " value=" + req.getHeader(nextName));
		}
		// The connection should be closed after this request
		// NB: this allows sending a "long response". Some clients
		// in particular java.net.URL in VMs > 1.1 that use HTTP/1.1
		// will block if
		// - the content length is not sent
		// - if Connection: close HTTP header is not sent.
		//
		// Since we don't know the content length we will assume
		// the underlying servlet engine will use chunked encoding.
		rsp.setHeader("Connection", "close");

		// Set content to plain text
		rsp.setContentType("text/plain");

		out = rsp.getOutputStream();
	}

	public void push(Event event) throws IOException {
		// Send the event as XML to the client and flush.
		// p("pushing event: " + event.toXML());
		out.print(event.toXML());
		out.flush();
	}

	public void stop() throws IOException {
	}

	private void debug(String s) {
		Log.debug("[XMLPushletAdapter]" + s);
	}
}

/*
 * $Log: XMLPushletAdapter.java,v $
 * Revision 1.5  2003/08/15 08:37:40  justb
 * fix/add Copyright+LGPL file headers and footers
 *
 * Revision 1.4  2003/08/13 14:00:00  justb
 * some testing for applets; no real change
 *
 * Revision 1.3  2003/08/12 09:57:06  justb
 * replaced all print statements to Log.*() calls
 *
 * Revision 1.2  2003/05/19 21:56:29  justb
 * various fixes for applet clients
 *
 * Revision 1.1  2003/05/18 16:12:28  justb
 * adding support for XML encoded Events
 */
